﻿using _05Net8Hosting.IOC;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05Net8Hosting.HostService
{
    
    public class MyBackgroundHostService : IHostedService
    {
        Timer _Timer;
        private ProductService productService;

        public MyBackgroundHostService(ProductService productService)
        {
            this.productService = productService;
        }


        /// <summary>
        /// 应用程序启动时 调用
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("定时任务开启。。。。。。。。。。。。");
            _Timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(2));
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            productService.GetProductService();
        }

        /// <summary>
        /// 应用程序停止时 调佣
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("项目停止");
            _Timer.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }
    }
}
